package cn.zhoushengdao.eyeprotector

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import java.util.concurrent.TimeUnit

class BootReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("EyeProtector", "BootReceiver onReceive")
        val validActions = setOf(
            Intent.ACTION_BOOT_COMPLETED,
            @Suppress("SpellCheckingInspection") "android.intent.action.QUICKBOOT_POWERON",
            Intent.ACTION_LOCKED_BOOT_COMPLETED
        )
        if (validActions.contains(intent.action)) {
            Log.d("EyeProtector", "BootReceiver onReceive validActions")
            WorkManager.getInstance(context).enqueue(
                OneTimeWorkRequestBuilder<ServiceStarterWorker>().setInitialDelay(
                    1, TimeUnit.SECONDS
                ).build()

            )
            WorkManager.getInstance(context).enqueue(
                OneTimeWorkRequestBuilder<ServiceStarterWorker>().setInitialDelay(
                    10, TimeUnit.SECONDS
                ).build()
            )
            WorkManager.getInstance(context).enqueue(
                OneTimeWorkRequestBuilder<ServiceStarterWorker>().setInitialDelay(
                    30, TimeUnit.SECONDS
                ).build()
            )
            Log.d("EyeProtector", "BootReceiver onReceive enqueue")
        }

        if (intent.action == Intent.ACTION_USER_UNLOCKED || intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) {
            Log.d("EyeProtector", "BootReceiver onReceive ACTION_USER_UNLOCKED")
            context.startForegroundService(Intent(context, EyeProtectorService::class.java))
            Log.d("EyeProtector", "BootReceiver onReceive startForegroundService")
        }
    }
}
